<template>
  <div class="container-fluid">
    <!-- 顶部导航栏 -->
    <header class="col-md-12 bg-primary text-white p-3">
      <div class="row align-items-center">
        <div class="col-auto">
          <h1>停车场管理系统</h1>
        </div>
        <div class="col"></div>
        <div class="col-auto text-right">
          <span>{{ username }}</span>
          <router-link to="/" class="btn btn-light ml-2">返回首页</router-link>
          <button @click="logout" class="btn btn-light ml-2">退出</button>
        </div>
      </div>
    </header>

    <!-- 主内容区域 -->
    <main class="col-md-12 mt-4">
      <div class="card">
        <div class="card-header bg-secondary text-white">
          <h2 class="text-center">收费管理</h2>
        </div>
        <div class="card-body">
          <div class="mb-4 bg-light p-3 rounded">
            <div class="row">
              <div class="col-md-3">
                <div class="form-group">
                  <label for="plateNumber">车牌号</label>
                  <input type="text" class="form-control" id="plateNumber" placeholder="请输入车牌号" v-model="searchParams.plateNumber" @input="searchPayments">
                </div>
              </div>
              <div class="col-md-3">
                <div class="form-group">
                  <label for="paymentStatus">支付状态</label>
                  <select class="form-control" id="paymentStatus" v-model="searchParams.status" @change="searchPayments">
                    <option value="">全部</option>
                    <option value="0">未支付</option>
                    <option value="1">已支付</option>
                  </select>
                </div>
              </div>
              <div class="col-md-3">
                <div class="form-group">
                  <label for="entryTime">入场时间</label>
                  <input type="datetime-local" class="form-control" id="entryTime" v-model="searchParams.entryTime" @change="searchPayments">
                </div>
              </div>
              <div class="col-md-3">
                <div class="form-group">
                  <label for="exitTime">出场时间</label>
                  <input type="datetime-local" class="form-control" id="exitTime" v-model="searchParams.exitTime" @change="searchPayments">
                </div>
              </div>
            </div>
          </div>
          
          <table class="table table-bordered">
            <thead>
              <tr>
                <th>序号</th>
                <th>车牌号</th>
                <th>车辆类型</th>
                <th>入场时间</th>
                <th>出场时间</th>
                <th>停车时长</th>
                <th>应付金额</th>
                <th>支付状态</th>
                <th>支付方式</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(payment, index) in paymentList" :key="payment.id">
                <td>{{ (this.currentPage - 1) * this.pageSize + index + 1 }}</td>
                <td>{{ payment.plateNumber }}</td>
                <td>{{ this.formatVehicleType(payment.type) }}</td>
                <td>{{ this.formatDateTime(payment.entryTime) }}</td>
                <td>{{ this.formatDateTime(payment.exitTime) }}</td>
                <td>{{ this.formatDuration(payment.duration) }}</td>
                <td>{{ payment.amount }}</td>
                <td>
                  <span :class="{
                    'text-success': payment.status === 1 || payment.status === '已支付',
                    'text-danger': payment.status === 0 || payment.status === '未支付'
                  }">
                    {{ this.formatPaymentStatus(payment.status) }}
                  </span>
                </td>
                <td>{{ this.formatPaymentMethod(payment.paymentType) }}</td>
              </tr>
            </tbody>
          </table>
          
          <!-- 分页控件 -->
          <div class="mt-4 text-center">
            <nav>
              <ul class="pagination justify-content-center">
                <li class="page-item" :class="{disabled: currentPage === 1}">
                  <button class="page-link" @click="handlePageChange(currentPage - 1)" :disabled="currentPage === 1">上一页</button>
                </li>
                <li v-for="page in Math.ceil(total / pageSize)" :key="page" class="page-item" :class="{active: page === currentPage}">
                  <button class="page-link" @click="handlePageChange(page)">{{ page }}</button>
                </li>
                <li class="page-item" :class="{disabled: currentPage === Math.ceil(total / pageSize)}">
                  <button class="page-link" @click="handlePageChange(currentPage + 1)" :disabled="currentPage === Math.ceil(total / pageSize)">下一页</button>
                </li>
              </ul>
            </nav>
            <div class="mt-2">
              <span>共 {{ total }} 条记录，第 {{ currentPage }} / {{ Math.ceil(total / pageSize) }} 页</span>
            </div>
          </div>
          

        </div>
      </div>
    </main>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'PaymentManageView',
  data() {
    return {
      username: '',
      paymentList: [],
      total: 0,
      currentPage: 1,
      pageSize: 8,
      searchParams: {
        plateNumber: '',
        status: '',
        entryTime: '',
        exitTime: ''
      }
    }
  },

  mounted() {
    this.username = localStorage.getItem('username') || '管理员'
    this.searchPayments()
  },
  methods: {
    logout() {
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('username')
      this.$router.push('/login')
    },
    

    
    searchPayments() {
      // 重置为第一页
      this.currentPage = 1
      this.loadPaymentsData()
    },

    loadPaymentsData() {
      // 调用后端API获取分页数据
      axios.get('/api/payments-vehicles-parking-records/page', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          plateNumber: this.searchParams.plateNumber,
          status: this.searchParams.status !== '' ? parseInt(this.searchParams.status) : null,
          entryTime: this.searchParams.entryTime,
          exitTime: this.searchParams.exitTime
        }
      })
      .then(response => {
        // 处理后端返回的PageInfo数据
        const pageInfo = response.data
        this.paymentList = pageInfo.list
        this.total = pageInfo.total
      })
      .catch(error => {
        // 处理错误
        console.error('获取支付记录失败:', error)
        alert('获取支付记录失败，请稍后再试')
      })
    },

    // 页码变化时触发
    handlePageChange(pageNum) {
      this.currentPage = pageNum
      this.loadPaymentsData()
    },
    
    viewPayment(id) {
      // 查看收费详情逻辑
      alert(`查看收费记录 ${id} 的详细信息`)
    },

    printInvoice(id) {
      // 打印发票逻辑
      alert(`打印收费记录 ${id} 的发票`)
    },
    
    // 格式化车辆类型
    formatVehicleType(type) {
      switch(type) {
        case 0: return '临时车'
        case 1: return '月租车'
        case 2: return '年租车'
        default: return '未知类型'
      }
    },
    
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      
      try {
        // 处理字符串格式的日期时间，确保格式为yyyy-MM-dd hh:mm:ss
        const date = new Date(dateTime)
        
        // 如果是无效的日期对象
        if (isNaN(date.getTime())) {
          // 尝试直接返回字符串（假设后端已经是正确格式）
          return dateTime
        }
        
        // 手动格式化日期时间
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      } catch (error) {
        // 发生错误时返回原始字符串
        return dateTime
      }
    },
    
    // 格式化停车时长（秒转换为小时分钟）
    formatDuration(seconds) {
      if (!seconds) return '0分钟'
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      if (hours > 0) {
        return `${hours}小时${minutes}分钟`
      } else {
        return `${minutes}分钟`
      }
    },
    
    // 格式化支付方式
    formatPaymentMethod(paymentType) {
      switch(paymentType) {
        case 0: return '现金'
        case 1: return '微信'
        case 2: return '支付宝'
        default: return '未支付'
      }
    },
    
    // 格式化支付状态
    formatPaymentStatus(status) {
      // 将状态转换为字符串进行比较，以处理数字和字符串两种形式
      const statusStr = String(status)
      switch(statusStr) {
        case '0': return '未支付'
        case '1': return '已支付'
        // 直接返回字符串状态值（例如："未支付"、"已支付"）
        default: return status
      }
    }
  }
}
</script>

<style >
/* 这里可以添加组件特定的样式 */
</style>